package com.ysd.lis.service.eq.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.WkFile;
import com.ysd.lis.entity.eq.EqEquipment;
import com.ysd.lis.entity.eq.EqEquipmentImage;
import com.ysd.lis.entity.eq.EqEquiptType;
import com.ysd.lis.entity.lab.LabInstrSetup;
import com.ysd.lis.mapper.WkFileMapper;
import com.ysd.lis.mapper.eq.EqEquipmentImageMapper;
import com.ysd.lis.mapper.eq.EqEquipmentMapper;
import com.ysd.lis.mapper.eq.EqEquiptTypeMapper;
import com.ysd.lis.mapper.lab.LabInstrSetupMapper;
import com.ysd.lis.request.eq.EqEquipmentDto;
import com.ysd.lis.request.eq.EqEquipmentVo;
import com.ysd.lis.service.eq.EqEquipmentService;
import com.ysd.util.PropertySlash;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备管理-设备类型 服务实现类
 * </p>
 *
 * @author prs
 * @since 2024-07-31
 */
@Service
public class EqEquipmentServiceImpl extends ServiceImpl<EqEquipmentMapper, EqEquipment> implements EqEquipmentService {

    @Autowired
    private EqEquipmentMapper eqEquipmentMapper;
    @Autowired
    private EqEquipmentService eqEquipmentService;

    @Autowired
    private EqEquipmentImageMapper eqEquipmentImageMapper;

    @Autowired
    private WkFileMapper wkFileMapper;

    @Autowired
    EqEquiptTypeMapper eqEquiptTypeMapper;

    @Autowired
    private LabInstrSetupMapper labInstrSetupMapper;

    @Value("${equipmentImagePath}")
    private String equipmentImagePath;

    @Override
    public Result findEqEquipmentPageList(EqEquipmentDto eqEquipmentDto) {

        List<EqEquiptType> returnList = new ArrayList<>();

        LambdaQueryWrapper<EqEquiptType> typeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        typeLambdaQueryWrapper.eq(EqEquiptType::getDelFlag, 0);
        typeLambdaQueryWrapper.orderByAsc(EqEquiptType::getParentId);
        List<EqEquiptType> eqEquiptTypes = eqEquiptTypeMapper.selectList(typeLambdaQueryWrapper);

        //查出顶端数据
        Optional<EqEquiptType> first = eqEquiptTypes.stream().filter(a -> a.getId().equals(eqEquipmentDto.getEquiptType())).findFirst();
        if (first.isPresent()) {
            EqEquiptType wkFolder = first.get();
            returnList.add(wkFolder);
            getChild(wkFolder, eqEquiptTypes, returnList);
        }
        List<String> equiptTypeList = returnList.stream().filter(a -> !StringUtils.isEmpty(a.getId())).map(EqEquiptType::getEquiptTypeCode).collect(Collectors.toList());

        SysUser sysUser = RedisUserManager.getUser();
        MPJLambdaWrapper<EqEquipment> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(EqEquipmentVo.class);
        lambdaQueryWrapper.selectAssociation("cre", SysUser.class, EqEquipmentVo::getCreatorName);
        lambdaQueryWrapper.selectAssociation("pur", SysUser.class, EqEquipmentVo::getPurchaserName);
        lambdaQueryWrapper.selectAssociation("man", SysUser.class, EqEquipmentVo::getManagerName);
        lambdaQueryWrapper.selectCollection(EqEquipmentImage.class, EqEquipmentVo::getEqEquipmentImages);

        lambdaQueryWrapper.leftJoin(SysUser.class, "cre", p -> p.eq(SysUser::getId, EqEquipment::getCreator).eq(SysUser::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysUser.class, "pur", p -> p.eq(SysUser::getUsername, EqEquipment::getPurchaser).eq(SysUser::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysUser.class, "man", p -> p.eq(SysUser::getUsername, EqEquipment::getManager).eq(SysUser::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(EqEquipmentImage.class, EqEquipmentImage::getEquiptId, EqEquipment::getId);
        if (ToolsUtils.isNotEmpty(sysUser)) {
            lambdaQueryWrapper.eq(EqEquipment::getOrgId, sysUser.getOrgId());
        }

        if (!StringUtils.isEmpty(eqEquipmentDto.getSearchValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(EqEquipment::getEquiptName, eqEquipmentDto.getSearchValue()).or().like(EqEquipment::getEquiptCode, eqEquipmentDto.getSearchValue()).or().like(EqEquipment::getSpecification, eqEquipmentDto.getSearchValue()));
        }
        if (!BeanUtil.isEmpty(eqEquipmentDto.getStartDate()) && !BeanUtil.isEmpty(eqEquipmentDto.getEndDate())) {
            Timestamp startTime = Timestamp.valueOf(eqEquipmentDto.getStartDate().substring(0, 10) + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(eqEquipmentDto.getEndDate().substring(0, 10) + " 23:59:59");
            lambdaQueryWrapper.ge(EqEquipment::getCreateTime, startTime);
            lambdaQueryWrapper.le(EqEquipment::getCreateTime, endTime);
        }
        lambdaQueryWrapper.eq(Objects.nonNull(eqEquipmentDto.getPoct()),EqEquipment::getPoct, eqEquipmentDto.getPoct());
        lambdaQueryWrapper.eq(EqEquipment::getDelFlag, 0);
        lambdaQueryWrapper.in(CollectionUtil.isNotEmpty(equiptTypeList), EqEquipment::getEquiptTypeCode, equiptTypeList);
        lambdaQueryWrapper.orderByDesc(EqEquipment::getCreateTime);
        List<EqEquipmentVo> eqEquipments = eqEquipmentMapper.selectJoinList(EqEquipmentVo.class, lambdaQueryWrapper);
        for (EqEquipmentVo eqEquipment : eqEquipments) {
            List<WkFile> list = wkFileMapper.selectList(new LambdaQueryWrapper<WkFile>().eq(WkFile::getBusinessId, eqEquipment.getId()).eq(WkFile::getDelFlag, 0));
            eqEquipment.setWkFiles(list);
        }
        return Result.succ(eqEquipments);
    }

    @Override
    public Result batchDeleteEqEquipment(List<EqEquipment> eqEquipments) {
        List<String> ids = eqEquipments.stream().map(EqEquipment::getId).collect(Collectors.toList());
        List<EqEquipmentImage> images = eqEquipmentImageMapper.selectList(new LambdaQueryWrapper<EqEquipmentImage>().in(EqEquipmentImage::getEquiptId, ids));
        List<WkFile> files = wkFileMapper.selectList(new LambdaQueryWrapper<WkFile>().in(WkFile::getFolderId, ids));
        //删除图片
        if (CollectionUtil.isNotEmpty(images)) {
            for (EqEquipmentImage image : images) {
                File file = new File(equipmentImagePath + PropertySlash.getSlash() + image.getImageName());
                if (file.isFile()) {
                    file.delete();
                }
            }
        }
        //删除文件
        if (CollectionUtil.isNotEmpty(files)) {
            for (WkFile wkFile : files) {
                File file = new File(wkFile.getDocPath());
                if (file.isFile()) {
                    file.delete();
                }
            }
        }
        wkFileMapper.delete(new LambdaQueryWrapper<WkFile>().in(WkFile::getFolderId, ids));
        eqEquipmentImageMapper.delete(new LambdaQueryWrapper<EqEquipmentImage>().in(EqEquipmentImage::getEquiptId, ids));
        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result findEqEquipmentList(EqEquipmentDto eqEquipmentDto) {
        MPJLambdaWrapper<EqEquipment> lambdaQueryWrapper = new MPJLambdaWrapper();
        lambdaQueryWrapper.selectAll(EqEquipment.class);
        lambdaQueryWrapper.eq(EqEquipment::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(eqEquipmentDto.getSearchValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(EqEquipment::getEquiptCode, eqEquipmentDto.getSearchValue())
                    .or().like(EqEquipment::getEquiptName, eqEquipmentDto.getSearchValue()));
        }
        lambdaQueryWrapper.orderByAsc(EqEquipment::getSeq);
        List<EqEquipment> eqEquipments = eqEquipmentMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "查询成功！", eqEquipments);

    }


    @Override
    public Result synInterData() {
        MPJLambdaWrapper<LabInstrSetup> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabInstrSetup.class);
        lambdaQueryWrapper.eq(LabInstrSetup::getPoct, "1");
        lambdaQueryWrapper.eq(LabInstrSetup::getDelFlag, 0);
        List<LabInstrSetup> labInstrSetups = labInstrSetupMapper.selectList(lambdaQueryWrapper);
        List<EqEquipment> eqEquipments = eqEquipmentMapper.selectList(new LambdaQueryWrapper<EqEquipment>().eq(EqEquipment::getDelFlag, 0).isNotNull(EqEquipment::getInstrCode));
        List<String> instrCodeList = eqEquipments.stream().map(EqEquipment::getInstrCode).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        List<LabInstrSetup> newList = labInstrSetups.stream()
                .filter(setup -> !instrCodeList.contains(setup.getInstrCode()))
                .collect(Collectors.toList());
        List<EqEquipment> eqEquipmentList=new ArrayList<>();
        for (LabInstrSetup labInstrSetup : newList) {
            EqEquipment eqEquipment=new EqEquipment();
            eqEquipment.setSpecification(labInstrSetup.getInstrCode());
            eqEquipment.setEquiptCode(labInstrSetup.getInstrCode());
            eqEquipment.setEquiptName(labInstrSetup.getInstrName());
            eqEquipment.setPoct(1);
            eqEquipment.setStatus("1");
            eqEquipment.setUsingStatus("0");
            eqEquipmentList.add(eqEquipment);
        }
        boolean b = eqEquipmentService.saveBatch(eqEquipmentList);
        if(b){
            return Result.succ(1, "批量新增成功", "");
        }else {
            return Result.fail(400, "批量新增失败", "");
        }
    }

    private void getChild(EqEquiptType wkFolder, List<EqEquiptType> folderList, List<EqEquiptType> returnList) {
        List<EqEquiptType> result = new ArrayList();
        for (EqEquiptType to : folderList) {
            if (ToolsUtils.isNotEmpty(to.getParentId()) && to.getParentId().equals(wkFolder.getId())) {
                result.add(to);
            }
        }

        for (EqEquiptType ma : result) {
            returnList.add(ma);
            getChild(ma, folderList, returnList);
        }

    }
}
